var salt = sessionStorage.getItem('usersalt');
var checkId = getQueryVariable("id");
var editCompanyId;
var arr ;
var flg = 0;

layui.use(['form', 'layer', 'upload'], function() {
	var $ = layui.jquery,
		form = layui.form,
		upload = layui.upload;

	layer = parent.layer === undefined ? layui.layer : top.layer,
		$ = layui.jquery;

	if(!sessionStorage.getItem('username')) {
		layer.msg('请先登录');
		setTimeout("top.location.href='../../../index.html'", 1000);
	}

	upload.render({
		elem: '#attId',
		url: url + 'attachment/upload',
		multiple: true,
		accept: 'file',
		exts: 'png|jpg|gif|jpeg|PNG|JPG|GIF|JPEG',
		before: function(obj) {},
		done: function(res) {
			//上传完毕
			console.log(res);
			if(res.code == 0) {
				flg++;
				console.log(res);
				arr=res.data.id;
				console.log(arr);

				var img = $('<div style="display:inline-block;position:relative;margin-right:20px;" id="picupdata' + flg + '"  ><div onclick="delpic(\'picupdata' + flg + '\',\'' + flg + '\',\'' + res.data.id + '\')" style="position:absolute;top:-4px;right:-5px;color:white;background:red;border:1px solid red;border-radius:50%;width:16px;height:16px"><i class="layui-icon" style="position:relative;top:-2px;right:0px;">&#x1006;</i></div><img id="pic' + res.data.id + '" onclick="lookbigpic(\'' + res.data.id + '\')" src="' + url + 'attachment/seekFile/' + res.data.id + '" width="100px" height="100px" class="picsty"/></div>');
				$('#picapp').html(img);

			}
		}
	});
	//获取危险源类型
	$.ajax({
		url: url + 'dangerList/getAllType',
		dataType: 'json',
		async: false,
		type: "POST",
		data: {
			Token: salt
		},
		success: function(data) {
			$('#type').empty();
			console.log(data);
			if(data.code == 0) {
				var list = data.data;
				var opt = '<option value="0">请选择</option>'
				for(var i = 0; i < list.length; i++) {
					if(list[i].name!='危险物料'&&list[i].name!='环境因素'){
						opt += '<option value="' + list[i].name + '" >' + list[i].name + '</option>'
					}
					
				}
				$('#type').append(opt);
				form.render();
			}
		},
		error: function(error) {
			console.log("获取失败");
		}
	});
	/*-------------编辑获取值.start-------------*/
	if(checkId != false) {
		$("#pageTitle").html("编辑危险源清单");
		$('#id').val(checkId);
		$.ajax({
			url: url + 'dangerList/getInfo',
			dataType: 'json',
			async: false,
			type: "POST",
			data: {
				Token: salt,
				id: checkId,
				type: 2
			},
			success: function(data) {
				if(data.code == 0) {
					var info = data.data;
					$("#seat").val(info.seat);
					$("#name").val(info.name);
					$("#numberNo").val(info.numberNo);
					$("#applyUnit").val(info.entName);
					$("#attId").val(info.entName);
					$('#type').find("option:contains('" + info.typeName + "')").attr("selected", true);

					var flg = 1;
					
					var img = $('<div style="display:inline-block;position:relative;margin-right:45px;" id="picupfile' + flg + '"  ><div onclick="delfile(\'picupfile' + flg + '\',\'' + flg + '\',\'' + info.attId + '\')" style="position:absolute;top:-2px;right:-21px;color:red;width:16px;height:16px"><i class="layui-icon" style="position:relative;top:-2px;right:0px;">&#x1006;</i></div><a style="color: blue;text-decoration: underline;" href="' + url + 'attachment/seekFile/' + info.attId + '"><img onclick="lookbigpic(\'' + info.attId  + '\')" src="' + url + 'attachment/seekFile/' + info.attId + '" width="100px" height="100px" class="picsty"></a></div>');
					$('#picapp').append(img);

					editCompanyId = info.entId;
					itemDangerArr = JSON.parse(info.danger);
					initItemDangerShow();
					itemRiskArr = JSON.parse(info.risk);
					initItemRiskShow();
					itemEventArr = JSON.parse(info.event);
					initItemEventShow();

					form.render();

				} else {
					setTimeout(function() {
						layer.msg(data.msg);
					}, 1000);
					checkId = false;
					initItemDangerShow();
				}
			},
			error: function(error) {
				console.log("获取失败");
			}
		});
	} else {
		$("#pageTitle").html("新增危险源清单");
		//新增初始化
		initItemDangerShow();
		initItemEventShow();
		initItemRiskShow();
	}
});

function GetQueryString(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	var r = window.location.search.substr(1).match(reg);
	if(r != null) return decodeURI(r[2]);
	return null;
}

/*-------------危险介质信息显示、隐藏.start-------------*/
var itemDangerArr = [{
	isShow: 1,
	danger: "",
	temperature: "常温"
}];

//危险介质信息
function initItemDangerShow() {
	var tbodyHtml = "";
	var rightTab = 1; //右侧添加按钮行数
	for(var i = 0; i < itemDangerArr.length; i++) {
		if(itemDangerArr[i].isShow == 1) {
			var contentHtml = ""; //检查项目内容html
			//内容框list
			/*-------------start-------------*/
			contentHtml +=
				"<tr id=\"item-content-danger-" + i + "\">" +
				"<td>" +
				"<div class=\"layui-input-inline ftdl\"><label class=\"fowei\">危险介质</label></div>" +
				"</td>" +
				"<td>" +
				"<input type=\"text\" class=\"layui-input\" id=\"item-content-" + i + "-textarea-1\"" +
				"onchange=\"setItemValue('item-content-" + i + "-textarea-1', " + i + ", 'danger',1)\"  value=\"" + itemDangerArr[i].danger + "\" />" +
				"</td>" +
				"<td>" +
				"<div class=\"layui-input-inline ftdl\"><label class=\"fowei\">温度</label></div>" +
				"</td>" +
				"<td>" +
				"<select id=\"item-select-danger-" + i + "-2\" onchange=\"setItemValue('item-select-danger-" + i + "-2'," + i + ", 'danger',2)\" class='layui-input layui-unselect' lay-ignore>" +
				"<option value=\"常温\">常温</option>" +
				"<option value=\"高温\">高温</option>" +
				"<option value=\"低温\">低温</option>" +
				"</select>" +
				"</td>" +
				"<td>" +
				"</td>" +
				"<td>" +
				"</td>" +
				"</tr>";
			/*-------------end-------------*/
			//按钮合并行数+1
			++rightTab;
			tbodyHtml += contentHtml;
			/*-------------检查项目.end-------------*/
		}
	}
	$("#addTable1").html(tbodyHtml);
	for(var i = 0; i < itemDangerArr.length; i++) {
		set_select_checked("item-select-danger-" + i + "-2", itemDangerArr[i].temperature);
	}
	setPosition();
}

//获取显示的危险介质数量-----start
function getShowItemNum() {
	var showNum = 0;
	for(var i = 0; i < itemDangerArr.length; i++) {
		if(itemDangerArr[i].isShow == 1) {
			++showNum;
		}
	}
	return showNum;
}

//增加危险介质项目
function addItem() {
	var showNum = getShowItemNum();
	itemDangerArr[showNum] = {
		isShow: 1,
		danger: "",
		temperature: "常温"
	};
	initItemDangerShow();
}

/*删除事件*/
function delfile(self, num, inde) {
	layer.confirm('你确定要删除吗？', {
		btn: ['确定', '取消'] //按钮
	}, function() {
		$('#' + self).remove();
		for(var i = 0; i < arr.length; i++) {
			if(arr[i] == inde) {
				arr.splice(i, 1);
			}
		}
		layer.msg('删除成功');
	}, function() {

	});
}

//删除危险介质项目
function delItem(index) {
	var showNum = getShowItemNum();
//	if(showNum == 1) {
//		return;
//	}
	for(var i = 0; i < itemDangerArr.length; i++) {
		var maxIndex = itemDangerArr.length - 1;
		if(i >= index && i < maxIndex) {
			itemDangerArr[i] = itemDangerArr[i + 1];
		}
	}
	itemDangerArr.pop();
	initItemDangerShow();
}

//++++++++++++++++++++++++++作业活动++++++++++++++++++++++++++
var itemEventArr = [{
	isShow: 1,
	content: "",
	frequency: "频繁",
	staff: ""
}];

function initItemEventShow() {
	var tbodyHtml = "";
	var rightTab = 1; //右侧添加按钮行数
	for(var i = 0; i < itemEventArr.length; i++) {
		if(itemEventArr[i].isShow == 1) {
			var contentHtml = ""; //检查项目内容html
			//内容框list
			/*-------------start-------------*/
			contentHtml +=
				"<tr id=\"item-content-event" + i + "\">" +
				"<td>" +
				"<div class=\"layui-input-inline ftdl\"><label class=\"fowei\">作业内容</label></div>" +
				"</td>" +
				"<td>" +
				"<input type=\"text\" class=\"layui-input\" placeholder=\"输入作业内容\"  id=\"item-risk-" + i + "-input-1\" onchange=\"setItemValue('item-risk-" + i + "-input-1', " + i + ", 'event',1)\" value=\"" + itemEventArr[i].content + "\" />" +
				"</td>" +

				"<td>" +
				"<div class=\"layui-input-inline ftdl\"><label class=\"fowei\">作业频次</label></div>" +
				"</td>" +
				"<td>" +
				"<select lay-ignore id=\"item-select-event-" + i + "-2\" class='layui-input layui-unselect' onchange=\"setItemValue('item-select-event-" + i + "-2'," + i + ", 'event',2)\">" +
				"<option value=\"频繁\">频繁</option>" +
				"<option value=\"0.5年\">0.5年</option>" +
				"<option value=\"1年\">1年</option>" +
				"<option value=\"—\">—</option>" +
				"</select>" +
				"</td>" +
				"<td>" +
				"<div class=\"layui-input-inline ftdl\"><label class=\"fowei\">涉及作业人员</label></div>" +
				"</td>" +
				"<td>" +
				"<input type=\"text\" class=\"layui-input\" placeholder=\"输入涉及作业人员\"  id=\"item-staff-" + i + "-input-1\"" +
				"onchange=\"setItemValue('item-staff-" + i + "-input-1', " + i + ", 'event',3)\" value=\"" + itemEventArr[i].staff + "\" />" +
				"</td>" +
				"</tr>";
			//			$(".item-select-event-0-2").val("0.5年");
			/*-------------end-------------*/
			//按钮合并行数+1
			++rightTab;
			tbodyHtml += contentHtml;
			/*-------------检查项目.end-------------*/
		}
	}
	$("#addTable2").html(tbodyHtml);

	for(var i = 0; i < itemEventArr.length; i++) {
		set_select_checked("item-select-event-" + i + "-2", itemEventArr[i].frequency);
	}

	setPosition();

}
//增加作业风险项目---开始
function getShowItemNumEvent() {
	var showNum = 0;
	for(var i = 0; i < itemRiskArr.length; i++) {
		if(itemRiskArr[i].isShow == 1) {
			++showNum;
		}
	}
	return showNum;
}

function addItemEvent() {
	var showNum = getShowItemNumEvent();
	itemEventArr[showNum] = {"isShow":1,"content":"","frequency":"频繁","staff":""};
	initItemEventShow();
}

//删除作业风险项目
function delItemEvent(index) {
	var showNum = getShowItemNumEvent();
	if(showNum == 1) {
		return;
	}
	for(var i = 0; i < itemEventArr.length; i++) {
		var maxIndex = itemEventArr.length - 1;
		if(i >= index && i < maxIndex) {
			itemEventArr[i] = itemEventArr[i + 1];
		}
	}
	itemEventArr.pop();
	initItemEventShow();
}

function getShowContentEvent(itemOrder) {
	var showNum = 0;
	for(var i = 0; i < itemEventArr[itemOrder].list.length; i++) {
		if(itemEventArr[itemOrder].list[i].isShow == 1) {
			++showNum;
		}
	}
	return showNum;
}

//++++++++++++++++++++++++++作业风险++++++++++++++++++++++++++
var itemRiskArr = [{
	isShow: 1,
	risk: "中毒",
	factor: "物",
	remarks: ""
}];

//作业风险
function initItemRiskShow() {
	var tbodyHtml = "";
	var rightTab = 1; //右侧添加按钮行数
	for(var i = 0; i < itemRiskArr.length; i++) {
		if(itemRiskArr[i].isShow == 1) {
			var contentHtml = ""; //检查项目内容html
			//内容框list
			/*-------------start-------------*/
			contentHtml +=
				"<tr id=\"item-content-risk-" + i + "\">" +
				"<td>" +
				"<div class=\"layui-input-inline ftdl\"><label class=\"fowei\">作业风险</label></div>" +
				"</td>" +
				"<td>" +
				"<select lay-ignore id=\"item-select-factor-" + i + "-2\" class='layui-input layui-unselect' onchange=\"setItemValue('item-select-factor-" + i + "-2'," + i + ", 'risk',3)\">" +
				"<option value=\"中毒\">中毒</option>" +
				"<option value=\"窒息\">窒息</option>" +
				"<option value=\"采光不良\">采光不良</option>" +
				"<option value=\"空间限制\">空间限制</option>" +
				"<option value=\"坠落\">坠落</option>" +
				"<option value=\"总合环境不良\">总合环境不良</option>" +
				"<option value=\"融油剂\">融油剂</option>" +
				"<option value=\"原油\">原油</option>" +
				"<option value=\"噪音\">噪音</option>" +
				"<option value=\"放射物\">放射物</option>" +
				"</select>" +
				"</td>" +

				"<td>" +
				"<div class=\"layui-input-inline ftdl\"><label class=\"fowei\">风险因素</label></div>" +
				"</td>" +
				"<td>" +
				"<select lay-ignore id=\"item-select-factor-w-" + i + "-2\" class='layui-input layui-unselect' onchange=\"setItemValue('item-select-factor-w-" + i + "-2'," + i + ", 'risk',2)\">" +
				"<option value=\"物\">物</option>" +
				"<option value=\"环境\">环境</option>" +
				"<option value=\"物理\">物理</option>" +
				"<option value=\"化学\">化学</option>" +
				"</select>" +
				"</td>" +

				"<td>" +
				"<div class=\"layui-input-inline ftdl\"><label class=\"fowei\">备注</label></div>" +
				"</td>" +
				"<td>" +
				"<input type=\"text\" class=\"layui-input\" placeholder=\"输入备注\"  id=\"item-risk-" + i + "-input-1\"" +
				"onchange=\"setItemValue('item-risk-" + i + "-input-1', " + i + ", 'risk',1)\" value=\"" + itemRiskArr[i].remarks + "\" />" +
				"</td>" +
				"</tr>";
			/*-------------end-------------*/
			//按钮合并行数+1
			++rightTab;
			tbodyHtml += contentHtml;
			/*-------------检查项目.end-------------*/
		}
	}
	$("#addTable3").html(tbodyHtml);
	for(var i = 0; i < itemRiskArr.length; i++) {
		set_select_checked("item-select-factor-" + i + "-2", itemRiskArr[i].risk);
		set_select_checked("item-select-factor-w-" + i + "-2", itemRiskArr[i].factor);
	}
	setPosition();
}

function set_select_checked(selectId, checkValue) {
	
	
		var obj = document.getElementById(selectId).options;
	for(i = 0; i < obj.length; i++) {
		if(obj[i].value == checkValue)
			obj[i].selected = true;
	}
	
	
}

//增加作业风险项目---开始
function getShowItemNumRisk() {
	var showNum = 0;
	for(var i = 0; i < itemRiskArr.length; i++) {
		if(itemRiskArr[i].isShow == 1) {
			++showNum;
		}
	}
	return showNum;
}

function addItemRisk() {
	var showNum = getShowItemNumRisk();
	itemRiskArr[showNum] = {
		isShow: 1,
		risk: "中毒",
		factor: "物",
		remarks: ""
	};
	initItemRiskShow();
}

//删除作业风险项目
function delItemRisk(index) {
	var showNum = getShowItemNumRisk();
//	if(showNum == 1) {
//		return;
//	}
	for(var i = 0; i < itemRiskArr.length; i++) {
		var maxIndex = itemRiskArr.length - 1;
		if(i >= index && i < maxIndex) {
			itemRiskArr[i] = itemRiskArr[i + 1];
		}
	}
	itemRiskArr.pop();
	initItemRiskShow();
}

function getShowContentRisk(itemOrder) {
	var showNum = 0;
	for(var i = 0; i < itemRiskArr[itemOrder].list.length; i++) {
		if(itemRiskArr[itemOrder].list[i].isShow == 1) {
			++showNum;
		}
	}
	return showNum;
}
//获取显示的作业风险数量----结束

//内容赋值
function setItemValue(id, itemOrder, type, index) {
	if(type == "danger") {
		console.log(id);
		if(index == 1) {
			itemDangerArr[itemOrder].danger = $("#" + id).val();
		} else {
			itemDangerArr[itemOrder].temperature = $("#" + id + " option:selected").val();
		}
	}
	if(type == "risk") {
		if(index == 1) {
			itemRiskArr[itemOrder].remarks = $("#" + id).val();
		} else if(index == 2) {
			itemRiskArr[itemOrder].factor = $("#" + id + " option:selected").val();
		} else if(index == 3) {
			itemRiskArr[itemOrder].risk = $("#" + id + " option:selected").val();
		}
	}
	if(type == "event") {
		if(index == 1) {
			itemEventArr[itemOrder].content = $("#" + id).val();
		} else if(index == 2) {
			itemEventArr[itemOrder].frequency = $("#" + id + " option:selected").val();
		} else if(index == 3) {
			itemEventArr[itemOrder].staff = $("#" + id).val();
		}
	}
}
//新增提交
function addDanger() {
	name = $.trim($("#name").val()); //名称
	if(name == "") {
		layer.msg('请填危险源名称');
		return;
	}
	var applyUnitId = getTreeVal().toString(); //适用单位id
	if(applyUnitId == 0 || applyUnitId == "") {
		if(checkId != false) { //编辑
			applyUnitId = editCompanyId;
		} else {
			layer.msg('请选择单位');
			return;
		}
	}
	var type = $("#type").val(); //类别
	var seat = $("#seat").val();
	var numberNo = $("#numberNo").val();

	var itemBool = judgeItemArr();
	if(!itemBool) {
		layer.msg('请填写完整检查项目');
		return;
	}
	if(checkId == false) { //新增时
		checkId = "";
	}
	var postUrl;

	if($('#id').val() == '') {
		postUrl = url + 'dangerList/addGM'
	} else {
		postUrl = url + 'dangerList/editGM'
	}

	$.ajax({
		url: postUrl,
		dataType: 'json',
		async: false,
		type: "POST",
		data: {
			id: $('#id').val(),
			Token: salt,
			name: name,
			seat: seat,
			number: numberNo,
			entId: applyUnitId,
			type: type,
			attId: arr.toString(),
			danger: JSON.stringify(itemDangerArr),
			event: JSON.stringify(itemEventArr),
			risk: JSON.stringify(itemRiskArr)
		},
		success: function(data) {
			if(data.code == 0) {
				var str = "新增危险源清单提交成功！";
				if(checkId != "") {
					str = "修改危险源清单提交成功！";
				}
				layer.alert(str, {
					btn: ['确定'] //按钮
				}, function(index) {
					layer.close(index);
					location.href = "page/dangerSource/list/list.html";

				});
			} else {
				layer.msg(data.msg);
			}
		},
		error: function(error) {
			console.log("获取失败");
		}
	});
}

/*-------------新增普通模板.start-------------*/
function judgeItemArr() {
	for(var i = 0; i < itemDangerArr.length; i++) {
		if(itemDangerArr[i].isShow == 1) {
			var danger = itemDangerArr[i].danger;
			if(danger == "") {
				return false;
			}
		}
	}
	return true;
}

function getAllCompany() {
	$.ajax({
		url: url + 'baseEnt/getAllEnt',
		dataType: 'json',
		async: false,
		type: "POST",
		data: {},
		success: function(data) {
			$('#applyUnitTree').empty();
			if(data.code == 0) {
				company = data.data;
			}
		},
		error: function(error) {
			console.log("获取失败");
		}
	});
}

/*------------单位节点树.start------------*/
function showUnitTree() {
	$('#applyUnitTree').show();
}

var company;
var arr = new Array();

getAllCompany();

var setting = {
	data: {
		simpleData: {
			enable: true
		}
	},
	check: {
		enable: true,
		chkStyle: "radio", //单选框
		radioType: "all" //对所有节点设置单选
	},
	callback: {
		onCheck: zTreeOnCheck
	}
};

$.fn.zTree.init($("#applyUnitTree"), setting, company);

function zTreeOnCheck(event, treeId, treeNode) {
	var checked = treeNode.checked;
	if(checked) {
		$('#applyUnit').val(treeNode.name);
	} else {
		$('#applyUnit').val("");
	}
	$('#applyUnitTree').hide();
};

function getTreeVal() {
	var unitTreeVal = [];
	var treeObj = $.fn.zTree.getZTreeObj("applyUnitTree");
	var nodes = treeObj.getCheckedNodes(true);
	for(var i = 0; i < nodes.length; i++) {
		unitTreeVal.push(nodes[i].id); //获取选中节点的值
	}
	return unitTreeVal;
}
/*------------单位节点树.end------------*/

/*-------------元素位置.start-------------*/
function setPosition() {
	var textareaHeight = $("textarea").height();
	$(".ctddel").height(textareaHeight + 2); //2为textarea线的高度
	$(".ctdadd").height(textareaHeight + 2);
	$(".cti-add").css("margin-top", textareaHeight - 16);
}
/*-------------元素位置.end-------------*/

/*-------------编辑获取值.end-------------*/
//
/*删除事件*/
function delpic(self, num, inde) {
	console.log(num);
	layer.confirm('你确定要删除吗？', {
		btn: ['确定', '取消'] //按钮
	}, function() {
		$('#' + self).remove();
		console.log(arr);
		for(var i = 0; i < arr.length; i++) {
			if(arr[i] == inde) {
				arr.splice(i, 1);
			}
		}

		console.log(arr);
		layer.msg('删除成功');
	}, function() {

	});
}


function lookbigpic(self) {
	console.log(self);
	var json = {
		"status": 1,
		"msg": "",
		"title": "",
		"id": 8,
		"start": 0,
		"data": [{
			"alt": "",
			"pid": 109,
			"src": url + "attachment/seekFile/" + self,
			"thumb": ""
		}]
	}
	layer.photos({
		photos: json,
		anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机
	});

}